package com.atguigu.gulimall.search.service.impl;

import cn.hutool.json.JSONUtil;
import com.atguigu.common.constant.SearchConstant;
import com.atguigu.common.to.SkuEsModel;
import com.atguigu.gulimall.search.config.EsConfig;
import com.atguigu.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @create: 2024/8/29
 * @author: gyhe10
 * @description:
 **/
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Resource
    private RestHighLevelClient restHighLevelClient;


    /**
     * 上架商品，添加商品文档到 ES 中的商品索引
     * @param skuEsModels
     */
    @Override
    public boolean productStatusToUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 在 ES 中创建商品索引，建立映射关系（已经在 Kibana 中完成）

        // 批量添加商品文档到 ES 中的商品索引
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            // 构造保存请求
            IndexRequest indexRequest = new IndexRequest(SearchConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String jsonStr = JSONUtil.toJsonStr(skuEsModel);
            indexRequest.source(jsonStr, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, EsConfig.COMMON_OPTIONS);
        // 如果批量添加商品文档到 ES 中有失败的情况，日志记录
        boolean hasFailures = bulk.hasFailures();
        if (hasFailures) {
            List<String> skuIdList = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
            log.error("商品上架失败，涉及商品 ID：{}", skuIdList);
        }
        return hasFailures;
    }
}
